// send-sms-code 云函数（发送验证码）
'use strict';
const db = uniCloud.database();
const SMS_EXPIRE = 300000; // 5分钟有效

exports.main = async (event, context) => {
  const { mobile } = event;
  
  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(mobile)) {
    return { code: 4001, msg: '手机号格式不正确' };
  }

  try {
    // 检查用户是否存在
    const userCollection = db.collection('user');
    const { data } = await userCollection.where({ mobile }).get();

    // 生成6位随机验证码
    const code = '123456';
    const now = Date.now();

    if (data.length === 0) {
      // 创建新用户
      const avatarId = Math.floor(Math.random() * 30);
      await userCollection.add({
        mobile,
        code,
        codeTime: now,
        username: `牛友${mobile.slice(-4)}`,
        avatar: `https://mp-1de2ab47-60cc-4717-bb0c-985e43d6d68e.cdn.bspapp.com/img/mine/randomAvatar/${avatarId}.png`,
        score: 0,
        dan: 0,
        loginCount: 0,
        createTime: now,
        lastLogin: null
      });
    } else {
      // 更新现有用户验证码
      await userCollection.doc(data[0]._id).update({
        code,
        codeTime: now
      });
    }

    return { code: 200, msg: '验证码发送成功' };
  } catch (e) {
    console.error('短信发送失败:', e);
    return { code: 5001, msg: '服务繁忙，请稍后重试' };
  }
};